/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package jmmos.gameserver.datatables;

import static jmmos.gameserver.model.itemcontainer.PcInventory.GOLD_ID;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

import javolution.util.FastList;
import javolution.util.FastMap;

import jmmos.Config;
import jmmos.MMODatabaseFactory;
import jmmos.gameserver.ThreadPoolManager;
import jmmos.gameserver.engines.DocumentEngine;
import jmmos.gameserver.engines.items.Item;
import jmmos.gameserver.idfactory.IdFactory;
import jmmos.gameserver.model.MMOObject;
import jmmos.gameserver.model.MMOWorld;
import jmmos.gameserver.model.actor.MMOAttackable;
import jmmos.gameserver.model.actor.instance.MMOEventMonsterInstance;
import jmmos.gameserver.model.actor.instance.MMOPcInstance;
import jmmos.gameserver.model.items.MMOArmor;
import jmmos.gameserver.model.items.MMOEtcItem;
import jmmos.gameserver.model.items.MMOItem;
import jmmos.gameserver.model.items.MMOWeapon;
import jmmos.gameserver.model.items.instance.MMOItemInstance;
import jmmos.gameserver.model.items.instance.MMOItemInstance.ItemLocation;
import jmmos.gameserver.model.items.type.MMOArmorType;
import jmmos.gameserver.model.items.type.MMOWeaponType;
import jmmos.gameserver.scripting.scriptengine.events.ItemCreateEvent;
import jmmos.gameserver.scripting.scriptengine.listeners.player.NewItemListener;
import jmmos.gameserver.util.GMAudit;

/**
 * This class ...
 * @version $Revision: 1.9.2.6.2.9 $ $Date: 2005/04/02 15:57:34 $
 */
public class ItemTable
{
	private static Logger _log = Logger.getLogger(ItemTable.class.getName());
	private static Logger _logItems = Logger.getLogger("item");
	
	private static FastList<NewItemListener> newItemListeners = new FastList<NewItemListener>().shared();
	
	public static final Map<String, Integer> _materials = new FastMap<>();
	public static final Map<String, Integer> _crystalTypes = new FastMap<>();
	public static final Map<String, Integer> _slots = new FastMap<>();
	public static final Map<String, MMOWeaponType> _weaponTypes = new FastMap<>();
	public static final Map<String, MMOArmorType> _armorTypes = new FastMap<>();
	
	private MMOItem[] _allTemplates;
	private final Map<Integer, MMOEtcItem> _etcItems;
	private final Map<Integer, MMOArmor> _armors;
	private final Map<Integer, MMOWeapon> _weapons;
	
	static
	{
		_materials.put("adamantaite", MMOItem.MATERIAL_ADAMANTAITE);
		_materials.put("blood_steel", MMOItem.MATERIAL_BLOOD_STEEL);
		_materials.put("bone", MMOItem.MATERIAL_BONE);
		_materials.put("bronze", MMOItem.MATERIAL_BRONZE);
		_materials.put("cloth", MMOItem.MATERIAL_CLOTH);
		_materials.put("chrysolite", MMOItem.MATERIAL_CHRYSOLITE);
		_materials.put("cobweb", MMOItem.MATERIAL_COBWEB);
		_materials.put("cotton", MMOItem.MATERIAL_FINE_STEEL);
		_materials.put("crystal", MMOItem.MATERIAL_CRYSTAL);
		_materials.put("damascus", MMOItem.MATERIAL_DAMASCUS);
		_materials.put("dyestuff", MMOItem.MATERIAL_DYESTUFF);
		_materials.put("fine_steel", MMOItem.MATERIAL_FINE_STEEL);
		_materials.put("fish", MMOItem.MATERIAL_FISH);
		_materials.put("gold", MMOItem.MATERIAL_GOLD);
		_materials.put("horn", MMOItem.MATERIAL_HORN);
		_materials.put("leather", MMOItem.MATERIAL_LEATHER);
		_materials.put("liquid", MMOItem.MATERIAL_LIQUID);
		_materials.put("mithril", MMOItem.MATERIAL_MITHRIL);
		_materials.put("oriharukon", MMOItem.MATERIAL_ORIHARUKON);
		_materials.put("paper", MMOItem.MATERIAL_PAPER);
		_materials.put("rune_xp", MMOItem.MATERIAL_RUNE_XP);
		_materials.put("rune_sp", MMOItem.MATERIAL_RUNE_SP);
		_materials.put("rune_remove_penalty", MMOItem.MATERIAL_RUNE_PENALTY);
		_materials.put("scale_of_dragon", MMOItem.MATERIAL_SCALE_OF_DRAGON);
		_materials.put("seed", MMOItem.MATERIAL_SEED);
		_materials.put("silver", MMOItem.MATERIAL_SILVER);
		_materials.put("steel", MMOItem.MATERIAL_STEEL);
		_materials.put("wood", MMOItem.MATERIAL_WOOD);
		
		_crystalTypes.put("s84", MMOItem.CRYSTAL_S84);
		_crystalTypes.put("s80", MMOItem.CRYSTAL_S80);
		_crystalTypes.put("s", MMOItem.CRYSTAL_S);
		_crystalTypes.put("a", MMOItem.CRYSTAL_A);
		_crystalTypes.put("b", MMOItem.CRYSTAL_B);
		_crystalTypes.put("c", MMOItem.CRYSTAL_C);
		_crystalTypes.put("d", MMOItem.CRYSTAL_D);
		_crystalTypes.put("none", MMOItem.CRYSTAL_NONE);
		
		// weapon types
		for (MMOWeaponType type : MMOWeaponType.values())
		{
			_weaponTypes.put(type.toString(), type);
		}
		
		// armor types
		for (MMOArmorType type : MMOArmorType.values())
		{
			_armorTypes.put(type.toString(), type);
		}
		
		_slots.put("shirt", MMOItem.SLOT_UNDERWEAR);
		_slots.put("lbracelet", MMOItem.SLOT_L_BRACELET);
		_slots.put("rbracelet", MMOItem.SLOT_R_BRACELET);
		_slots.put("talisman", MMOItem.SLOT_DECO);
		_slots.put("chest", MMOItem.SLOT_CHEST);
		_slots.put("fullarmor", MMOItem.SLOT_FULL_ARMOR);
		_slots.put("head", MMOItem.SLOT_HEAD);
		_slots.put("hair", MMOItem.SLOT_HAIR);
		_slots.put("hairall", MMOItem.SLOT_HAIRALL);
		_slots.put("underwear", MMOItem.SLOT_UNDERWEAR);
		_slots.put("back", MMOItem.SLOT_BACK);
		_slots.put("neck", MMOItem.SLOT_NECK);
		_slots.put("legs", MMOItem.SLOT_LEGS);
		_slots.put("feet", MMOItem.SLOT_FEET);
		_slots.put("gloves", MMOItem.SLOT_GLOVES);
		_slots.put("chest,legs", MMOItem.SLOT_CHEST | MMOItem.SLOT_LEGS);
		_slots.put("belt", MMOItem.SLOT_BELT);
		_slots.put("rhand", MMOItem.SLOT_R_HAND);
		_slots.put("lhand", MMOItem.SLOT_L_HAND);
		_slots.put("lrhand", MMOItem.SLOT_LR_HAND);
		_slots.put("rear;lear", MMOItem.SLOT_R_EAR | MMOItem.SLOT_L_EAR);
		_slots.put("rfinger;lfinger", MMOItem.SLOT_R_FINGER | MMOItem.SLOT_L_FINGER);
		_slots.put("wolf", MMOItem.SLOT_WOLF);
		_slots.put("greatwolf", MMOItem.SLOT_GREATWOLF);
		_slots.put("hatchling", MMOItem.SLOT_HATCHLING);
		_slots.put("strider", MMOItem.SLOT_STRIDER);
		_slots.put("babypet", MMOItem.SLOT_BABYPET);
		_slots.put("none", MMOItem.SLOT_NONE);
		
		// retail compatibility
		_slots.put("onepiece", MMOItem.SLOT_FULL_ARMOR);
		_slots.put("hair2", MMOItem.SLOT_HAIR2);
		_slots.put("dhair", MMOItem.SLOT_HAIRALL);
		_slots.put("alldress", MMOItem.SLOT_ALLDRESS);
		_slots.put("deco1", MMOItem.SLOT_DECO);
		_slots.put("waist", MMOItem.SLOT_BELT);
		
	}
	
	/**
	 * Returns instance of ItemTable
	 * @return ItemTable
	 */
	public static ItemTable getInstance()
	{
		return SingletonHolder._instance;
	}
	
	/**
	 * @return a new object Item
	 */
	public Item newItem()
	{
		return new Item();
	}
	
	/**
	 * Constructor.
	 */
	protected ItemTable()
	{
		_etcItems = new FastMap<>();
		_armors = new FastMap<>();
		_weapons = new FastMap<>();
		load();
	}
	
	private void load()
	{
		int highest = 0;
		_armors.clear();
		_etcItems.clear();
		_weapons.clear();
		for (MMOItem item : DocumentEngine.getInstance().loadItems())
		{
			if (highest < item.getItemId())
			{
				highest = item.getItemId();
			}
			if (item instanceof MMOEtcItem)
			{
				_etcItems.put(item.getItemId(), (MMOEtcItem) item);
			}
			else if (item instanceof MMOArmor)
			{
				_armors.put(item.getItemId(), (MMOArmor) item);
			}
			else
			{
				_weapons.put(item.getItemId(), (MMOWeapon) item);
			}
		}
		buildFastLookupTable(highest);
		_log.log(Level.INFO, getClass().getSimpleName() + ": Loaded: " + _etcItems.size() + " Etc Items");
		_log.log(Level.INFO, getClass().getSimpleName() + ": Loaded: " + _armors.size() + " Armor Items");
		_log.log(Level.INFO, getClass().getSimpleName() + ": Loaded: " + _weapons.size() + " Weapon Items");
		_log.log(Level.INFO, getClass().getSimpleName() + ": Loaded: " + (_etcItems.size() + _armors.size() + _weapons.size()) + " Items in total.");
	}
	
	/**
	 * Builds a variable in which all items are putting in in function of their ID.
	 * @param size
	 */
	private void buildFastLookupTable(int size)
	{
		// Create a FastLookUp Table called _allTemplates of size : value of the highest item ID
		_log.info(getClass().getSimpleName() + ": Highest item id used:" + size);
		_allTemplates = new MMOItem[size + 1];
		
		// Insert armor item in Fast Look Up Table
		for (MMOArmor item : _armors.values())
		{
			_allTemplates[item.getItemId()] = item;
		}
		
		// Insert weapon item in Fast Look Up Table
		for (MMOWeapon item : _weapons.values())
		{
			_allTemplates[item.getItemId()] = item;
		}
		
		// Insert etcItem item in Fast Look Up Table
		for (MMOEtcItem item : _etcItems.values())
		{
			_allTemplates[item.getItemId()] = item;
		}
	}
	
	/**
	 * Returns the item corresponding to the item ID
	 * @param id : int designating the item
	 * @return MMOItem
	 */
	public MMOItem getTemplate(int id)
	{
		if ((id >= _allTemplates.length) || (id < 0))
		{
			return null;
		}
		
		return _allTemplates[id];
	}
	
	/**
	 * Create the MMOItemInstance corresponding to the Item Identifier and quantitiy add logs the activity. <B><U> Actions</U> :</B> <li>Create and Init the MMOItemInstance corresponding to the Item Identifier and quantity</li> <li>Add the MMOItemInstance object to _allObjects of MMOworld</li> <li>Logs
	 * Item creation according to log settings</li>
	 * @param process : String Identifier of process triggering this action
	 * @param itemId : int Item Identifier of the item to be created
	 * @param count : int Quantity of items to be created for stackable items
	 * @param actor : MMOPcInstance Player requesting the item creation
	 * @param reference : Object Object referencing current action like NPC selling item or previous item in transformation
	 * @return MMOItemInstance corresponding to the new item
	 */
	public MMOItemInstance createItem(String process, int itemId, long count, MMOPcInstance actor, Object reference)
	{
		if (!fireNewItemListeners(process, itemId, count, actor, reference))
		{
			return null;
		}
		
		// Create and Init the MMOItemInstance corresponding to the Item Identifier
		MMOItemInstance item = new MMOItemInstance(IdFactory.getInstance().getNextId(), itemId);
		
		if (process.equalsIgnoreCase("loot"))
		{
			ScheduledFuture<?> itemLootShedule;
			if ((reference instanceof MMOAttackable) && ((MMOAttackable) reference).isRaid()) // loot privilege for raids
			{
				MMOAttackable raid = (MMOAttackable) reference;
				// if in CommandChannel and was killing a World/RaidBoss
				if ((raid.getFirstCommandChannelAttacked() != null) && !Config.AUTO_LOOT_RAIDS)
				{
					item.setOwnerId(raid.getFirstCommandChannelAttacked().getLeaderObjectId());
					itemLootShedule = ThreadPoolManager.getInstance().scheduleGeneral(new ResetOwner(item), Config.LOOT_RAIDS_PRIVILEGE_INTERVAL);
					item.setItemLootShedule(itemLootShedule);
				}
			}
			else if (!Config.AUTO_LOOT || ((reference instanceof MMOEventMonsterInstance) && ((MMOEventMonsterInstance) reference).eventDropOnGround()))
			{
				item.setOwnerId(actor.getObjectId());
				itemLootShedule = ThreadPoolManager.getInstance().scheduleGeneral(new ResetOwner(item), 15000);
				item.setItemLootShedule(itemLootShedule);
			}
		}
		
		if (Config.DEBUG)
		{
			_log.fine(getClass().getSimpleName() + ": Item created  oid:" + item.getObjectId() + " itemid:" + itemId);
		}
		
		// Add the MMOItemInstance object to _allObjects of MMOworld
		MMOWorld.getInstance().storeObject(item);
		
		// Set Item parameters
		if (item.isStackable() && (count > 1))
		{
			item.setCount(count);
		}
		
		if (Config.LOG_ITEMS && !process.equals("Reset"))
		{
			if (!Config.LOG_ITEMS_SMALL_LOG || (Config.LOG_ITEMS_SMALL_LOG && (item.isEquipable() || (item.getItemId() == GOLD_ID))))
			{
				LogRecord record = new LogRecord(Level.INFO, "CREATE:" + process);
				record.setLoggerName("item");
				record.setParameters(new Object[]
				{
					item,
					actor,
					reference
				});
				_logItems.log(record);
			}
		}
		
		if (actor != null)
		{
			if (actor.isGM())
			{
				String referenceName = "no-reference";
				if (reference instanceof MMOObject)
				{
					referenceName = (((MMOObject) reference).getName() != null ? ((MMOObject) reference).getName() : "no-name");
				}
				else if (reference instanceof String)
				{
					referenceName = (String) reference;
				}
				String targetName = (actor.getTarget() != null ? actor.getTarget().getName() : "no-target");
				if (Config.GMAUDIT)
				{
					GMAudit.auditGMAction(actor.getName() + " [" + actor.getObjectId() + "]", process + "(id: " + itemId + " count: " + count + " name: " + item.getItemName() + " objId: " + item.getObjectId() + ")", targetName, "MMOObject referencing this action is: " + referenceName);
				}
			}
		}
		
		return item;
	}
	
	public MMOItemInstance createItem(String process, int itemId, int count, MMOPcInstance actor)
	{
		return createItem(process, itemId, count, actor, null);
	}
	
	/**
	 * Returns a dummy item.<br>
	 * <U><I>Concept :</I></U><BR>
	 * Dummy item is created by setting the ID of the object in the world at null value
	 * @param itemId : int designating the item
	 * @return MMOItemInstance designating the dummy item created
	 */
	public MMOItemInstance createDummyItem(int itemId)
	{
		MMOItem item = getTemplate(itemId);
		if (item == null)
		{
			return null;
		}
		MMOItemInstance temp = new MMOItemInstance(0, item);
		return temp;
	}
	
	/**
	 * Destroys the MMOItemInstance.<br>
	 * <B><U> Actions</U> :</B>
	 * <ul>
	 * <li>Sets MMOItemInstance parameters to be unusable</li>
	 * <li>Removes the MMOItemInstance object to _allObjects of MMOworld</li>
	 * <li>Logs Item deletion according to log settings</li>
	 * </ul>
	 * @param process a string identifier of process triggering this action.
	 * @param item the item instance to be destroyed.
	 * @param actor the player requesting the item destroy.
	 * @param reference the object referencing current action like NPC selling item or previous item in transformation.
	 */
	public void destroyItem(String process, MMOItemInstance item, MMOPcInstance actor, Object reference)
	{
		synchronized (item)
		{
			long old = item.getCount();
			item.setCount(0);
			item.setOwnerId(0);
			item.setLocation(ItemLocation.VOID);
			item.setLastChange(MMOItemInstance.REMOVED);
			
			MMOWorld.getInstance().removeObject(item);
			IdFactory.getInstance().releaseId(item.getObjectId());
			
			if (Config.LOG_ITEMS)
			{
				if (!Config.LOG_ITEMS_SMALL_LOG || (Config.LOG_ITEMS_SMALL_LOG && (item.isEquipable() || (item.getItemId() == GOLD_ID))))
				{
					LogRecord record = new LogRecord(Level.INFO, "DELETE:" + process);
					record.setLoggerName("item");
					record.setParameters(new Object[]
					{
						item,
						"PrevCount(" + old + ")",
						actor,
						reference
					});
					_logItems.log(record);
				}
			}
			
			if (actor != null)
			{
				if (actor.isGM())
				{
					String referenceName = "no-reference";
					if (reference instanceof MMOObject)
					{
						referenceName = (((MMOObject) reference).getName() != null ? ((MMOObject) reference).getName() : "no-name");
					}
					else if (reference instanceof String)
					{
						referenceName = (String) reference;
					}
					String targetName = (actor.getTarget() != null ? actor.getTarget().getName() : "no-target");
					if (Config.GMAUDIT)
					{
						GMAudit.auditGMAction(actor.getName() + " [" + actor.getObjectId() + "]", process + "(id: " + item.getItemId() + " count: " + item.getCount() + " itemObjId: " + item.getObjectId() + ")", targetName, "MMOObject referencing this action is: " + referenceName);
					}
				}
			}
			
			// if it's a pet control item, delete the pet as well
			if (item.getItem().isPetItem())
			{
				try (Connection con = MMODatabaseFactory.getInstance().getConnection();
					PreparedStatement statement = con.prepareStatement("DELETE FROM pets WHERE item_obj_id=?"))
				{
					// Delete the pet in db
					statement.setInt(1, item.getObjectId());
					statement.execute();
				}
				catch (Exception e)
				{
					_log.log(Level.WARNING, "could not delete pet objectid:", e);
				}
			}
		}
	}
	
	public void reload()
	{
		load();
		EnchantHPBonusData.getInstance().load();
	}
	
	protected static class ResetOwner implements Runnable
	{
		MMOItemInstance _item;
		
		public ResetOwner(MMOItemInstance item)
		{
			_item = item;
		}
		
		@Override
		public void run()
		{
			_item.setOwnerId(0);
			_item.setItemLootShedule(null);
		}
	}
	
	public Set<Integer> getAllArmorsId()
	{
		return _armors.keySet();
	}
	
	public Set<Integer> getAllWeaponsId()
	{
		return _weapons.keySet();
	}
	
	public int getArraySize()
	{
		return _allTemplates.length;
	}
	
	private static class SingletonHolder
	{
		protected static final ItemTable _instance = new ItemTable();
	}
	
	// Listeners
	
	/**
	 * Fires all the new item listeners, if any
	 * @param process
	 * @param itemId
	 * @param count
	 * @param actor
	 * @param reference
	 * @return
	 */
	private boolean fireNewItemListeners(String process, int itemId, long count, MMOPcInstance actor, Object reference)
	{
		if (!newItemListeners.isEmpty() && (actor != null))
		{
			ItemCreateEvent event = new ItemCreateEvent();
			event.setItemId(itemId);
			event.setPlayer(actor);
			event.setCount(count);
			event.setProcess(process);
			event.setReference(reference);
			for (NewItemListener listener : newItemListeners)
			{
				if (listener.containsItemId(itemId))
				{
					if (!listener.onCreate(event))
					{
						return false;
					}
				}
			}
		}
		return true;
	}
	
	/**
	 * Adds a new item listener
	 * @param listener
	 */
	public static void addNewItemListener(NewItemListener listener)
	{
		if (!newItemListeners.contains(listener))
		{
			newItemListeners.add(listener);
		}
	}
	
	/**
	 * Removes a new item listener
	 * @param listener
	 */
	public static void removeNewItemListener(NewItemListener listener)
	{
		newItemListeners.remove(listener);
	}
}
